#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAME_LENGTH 20
#define MAX_PROCESSES 10

typedef struct {
	char name[MAX_NAME_LENGTH];
	int remainingTime;
	int executedTime;
	int isFinished;
} Process;

typedef struct {
	Process *processes;
	int front, rear;
} Queue;

void initQueue(Queue *queue) {
	queue->processes = (Process *)malloc(MAX_PROCESSES * sizeof(Process));
	queue->front = queue->rear = 0;
}

int isQueueEmpty(Queue *queue) {
	return queue->front == queue->rear;
}

void enqueue(Queue *queue, Process process) {
	queue->processes[queue->rear] = process;
	queue->rear = (queue->rear + 1) % MAX_PROCESSES;
}

Process dequeue(Queue *queue) {
	Process process = queue->processes[queue->front];
	queue->front = (queue->front + 1) % MAX_PROCESSES;
	return process;
}

void createProcess(Queue *queue, int numProcesses) {
	Process process;
	for (int i = 0; i < numProcesses; i++) {
		printf("请输入进程 %d 的名称: ", i + 1);
		scanf("%s", process.name);
		printf("请输入进程 %d 的运行时间: ", i + 1);
		scanf("%d", &process.remainingTime);
		process.executedTime = 0;
		process.isFinished = 0;
		enqueue(queue, process);
	}
}

void schedule(Queue *queue, int timeSlice) {
	int currentTime = 0;
	while (!isQueueEmpty(queue)) {
		Process process = dequeue(queue);
		int slice = process.remainingTime < timeSlice ? process.remainingTime : timeSlice;
		printf("当前时间: %d, 运行进程 %s, CPU时间 %d-%d, 运行时间 %d 单位\n", currentTime, process.name, process.executedTime, process.executedTime + slice, slice);
		process.remainingTime -= slice;
		process.executedTime += slice;
		if (process.remainingTime > 0) {
			if (process.executedTime % timeSlice == 0) {
				printf("进程 %s 的 CPU 占用时间达到时间片轮转时间，将重新放回队列末尾\n", process.name);
				enqueue(queue, process);
			} else {
				printf("进程 %s 需要 %d 单位时间完成\n", process.name, process.remainingTime);
				enqueue(queue, process);
			}
		} else {
			process.isFinished = 1;
			printf("进程 %s 已完成\n", process.name);
		}
		currentTime += slice;
	}
}

int main() {
	int numProcesses, timeSlice;
	Queue queue;
	
	initQueue(&queue);
	
	printf("请输入进程数量: ");
	scanf("%d", &numProcesses);
	
	createProcess(&queue, numProcesses);
	
	printf("请输入时间片大小: ");
	scanf("%d", &timeSlice);
	
	schedule(&queue, timeSlice);
	
	free(queue.processes);
	
	return 0;
}

